package com.mlm.mlmapp.activity;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.OnRecyclerViewScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.point_list)
public class PointListActivity extends BaseActivity implements HTTPCons {
	public static final int REQUEST_CODE_POINT = 1900;
	@Pref
	Prefs_ pref;
	@DimensionRes(R.dimen.recyclerview_mycomments_space)
	float commentImagesMargin;
	@DimensionRes
	float comments_images_edge;
	@ColorRes
	int red;
	@ColorRes
	int lightgreytext;
	@ColorRes
	int blacktext;
	public String currentJson = "";
	private AQuery aq;
	private PointListAdapter adapter;
	List<JSONObject> pointListDataset;
	@ViewById
	RecyclerView rv_coupons;
	@Extra
	String couponid;
	@Extra
	String id;
	@DrawableRes
	Drawable grey_edge_btn_long;
	int currPage=2;
	@AfterViews
	public void init() {
		String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}
		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		pointListDataset = new ArrayList<>();
		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
		rv_coupons.setLayoutManager(layoutManager);
		rv_coupons
				.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0, 0));
		rv_coupons.setItemAnimator(new RecyclAnimation());
		adapter = new PointListAdapter(PointListActivity.this, pointListDataset);
		rv_coupons.setAdapter(adapter);
		getPointList(0);
		rv_coupons.setOnScrollListener(new OnRecyclerViewScrollListener() {
			
			@Override
			public void onLoadMore() {
				// TODO Auto-generated method stub
				getPointList(currPage);
				currPage++;
			}
		});

	}

	void getPointList(final int page) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		pairs.add(new BasicNameValuePair("page", page + ""));
		CommonUtils.postRequest4Array(get_point_list_action, aq,
				new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
							AjaxStatus status) {

						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						// TODO Auto-generated method stub
						if (status.getCode() == 200) {

							for (int i = 0; i < array.length(); i++) {
								JSONObject obj;
								try {
									obj = array.getJSONObject(i);
									pointListDataset.add(obj);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}

							if( pointListDataset.size()<=0){
								pointListDataset.add(null);
							}
							adapter.notifyDataSetChanged();

						} else if (status.getCode() == 500) {
							Toast.makeText(aq.getContext(),
									"服务器异常:" + status.getCode(),
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_SHORT).show();

						}
					}

				}, pairs);
	}

	class PointListAdapter extends
			RecyclerView.Adapter<RecyclerView.ViewHolder> {
		private List<JSONObject> array;

		public PointListAdapter(Context con, List<JSONObject> array) {
			this.array = array;

		}

		@Override
		public int getItemCount() {
			return array.size();
		}

		public boolean isPositionHeader(int position) {
			return position == 0;
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
				int viewType) {

			PointViewHolder holder = null;
			if (array.size() == 1 && array.get(viewType) == null) {

				final View view = LayoutInflater.from(PointListActivity.this).inflate(
						R.layout.noitem, parent, false);
				ImageView iv = (ImageView) view.findViewById(R.id.iv_default);
				TextView t = (TextView) view.findViewById(R.id.tv_content);
				iv.setImageResource(R.drawable.noitem_points);
				t.setText("暂无积分记录");
				holder = new PointViewHolder(view);
				holder.itemView.setTag(com.mlm.mlmapp.cons.Constants.IS_EMPTY);

			} else {
				final View view =LayoutInflater.from(PointListActivity.this).inflate(
						R.layout.point_list_item, parent, false);
				holder = new PointViewHolder(view);
			}
			return holder;

//			// TODO Auto-generated method stub
//			final PointViewHolder holder = new PointViewHolder(LayoutInflater
//					.from(PointListActivity.this).inflate(
//							R.layout.point_list_item, parent, false));
//			return holder;

		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder,
				int position) {
			if (holder.itemView.getTag() != null) {
				if ((boolean) holder.itemView.getTag())
					return;
			}

			// TODO Auto-generated method stub
			final PointViewHolder vholder = (PointViewHolder) holder;
			final JSONObject temp = array.get(position);
			int type = getJsonInt(temp, "type");
			int balance = getJsonInt(temp, "balance");
			String integral = getJsonString(temp, "integral");
			String createdDate = getJsonString(temp, "createdDate");
			if (type == 1) {
				// 收入
				vholder.tv_name.setText("收入");
				vholder.tv_comvair.setText("+" + integral);

			} else {
				// 支出
				vholder.tv_name.setText("支出");
				vholder.tv_comvair.setText("-" + integral);
			}
			vholder.tv_date.setText(createdDate);
			vholder.tv_balance.setText(getString(R.string.point_balance,
					balance));

		}

		public class PointViewHolder extends RecyclerView.ViewHolder {
			TextView tv_name;
			TextView tv_date;
			TextView tv_balance;
			TextView tv_comvair;

			public PointViewHolder(View itemView) {
				super(itemView);
				this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
				this.tv_date = (TextView) itemView.findViewById(R.id.tv_date);
				this.tv_balance = (TextView) itemView
						.findViewById(R.id.tv_balance);
				this.tv_comvair = (TextView) itemView
						.findViewById(R.id.tv_comvair);

			}
		}
	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
//		Intent data = new Intent();
//
//		setResult(AN_REQUEST_CODE, data);
//		UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).startForResult(AN_REQUEST_CODE);
		this.finish();
	}

}
